// pages/exam/exam.js
const app = getApp()
Page({
  
  /**
   * 页面的初始数据
   */
  data: {
    select:['A','B','C','D'],
    choose:0,
    question:[],
    showFlag:false,
    errorFlag:[],
    answerCorrect:0,
    answerError:0,
    currentQuestionIndex:0,
    current:0,
    notebook:[],
    showModul:false,
    showModulCard:false,
    soonName:'',
    fatherName:'',
    basicVisible: false,
    scrollVisible: false,
    closeVisible: false,
    visible1:false,
    actions1: [
        {
            text: '白天模式',
            key: 'light',
        },
        {
            text: '夜间模式',
            key: 'night',
        },{
            text: '绿色护眼',
            key: 'green',
        }
    ],
    bgColor:"#ffffff",
    font_Color:"#000000"
    
  },
  /* 滑动位置 */
  sliderTouch(e){
      /* console.log('当前在第几个位置',e.detail.current); */
      this.setData({
          current:e.detail.current
      })
      if(e.detail.current==this.data.question.length-1){
          wx.showToast({
            title: '最后一题',
          })
      }
  },
  /* 预览图片 */
  previewImg(e){
    console.log('预览照片');
    wx.previewImage({
        urls: this.data.notebook,
    })
  },
  /* 删除照片 */
  delImg(e){
    wx.showModal({
        title:'确定删除?',
        success:(res)=>{
            if(res.confirm){
                var index = e.currentTarget.dataset.index
                console.log(index);
                var temp =this.data.notebook
                temp.splice(index,1)
                console.log("你好",temp);
                this.setData({
                    notebook:temp
                })
            }
        }
    })
    
  },
  /* 获取笔记内容 */
  collNote(e){
      console.log(e.detail.value);
      this.setData({
          notoWrite:e.detail.value
      })
  },
  /* 提交笔记 */
  subMitNotbook(){
      if(this.data.notoWrite.length==0){
          wx.showToast({
            title: '您还没记录笔记',
            icon:'none'
          })
          return
      }
      wx.showLoading({
        title: '加入中',
      })
      wx.request({
        url: app.globalData.baseUrl+'/user/save_notes',
        method:"POST",
        data:{
            exid:this.data.question[this.data.current].id,
            url:this.data.notebook,
            notes:this.data.notoWrite,
            userid:wx.getStorageSync('userInfo').id
        },success:(res)=>{
            wx.hideLoading()
            if(res.data.success==true){
                this.setData({
                    notebook:[],
                    notoWrite:"",
                    showModul:false
                })
            }else{
                wx.showToast({
                  title: 'server Error',
                })
            }
        },fail:(res)=>{
            wx.showToast({
                title: 'server Error',
            })
        }
      })
  },
  /**,
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
      console.log(options.id);
      this.get_exam_quetions(options.id)
  },
  /* 获取题目 */
  get_exam_quetions(id){
    wx.request({
        url: app.globalData.baseUrl+'/user/get_quetion_exam',
        method:"POST",
        data:{
            id:id
        },success:(res)=>{
            wx.hideLoading()
            console.log(res);
            if(res.data.success==true){
                var temp = []
                for(var i=0;i<res.data.data.length;i++){
                    var quetion_obj=res.data.data[i]
                    quetion_obj.selectAnswer_qutions=""
                    quetion_obj.selectFlag=[
                        {flag:false,value:"A"},
                        {flag:false,value:"B"},
                        {flag:false,value:"C"},
                        {flag:false,value:"D"},
                        {flag:false,value:"E"},
                        {flag:false,value:"F"},
                        {flag:false,value:"G"},
                    ]
                    if(this.isUrl(res.data.data[i].question_stem)==true){
                        quetion_obj.titleStyle=true
                    }else{
                        quetion_obj.titleStyle=false
                    }
                    temp.push(quetion_obj)
                }
                this.setData({
                    question:temp
                })
                console.log("刷题信息",temp);
            }else{
                wx.showToast({
                  title: '暂无题库',
                })
            }
        },fail:(res)=>{
            wx.hideLoading()
            console.log(res);
        }
      })
  },
  /* 选择题 */
  bindSelect(e){
    var indexFather = e.currentTarget.dataset.index;
    var indexSoon = parseInt(e.currentTarget.dataset.item) - 1;
    var questions = this.data.question;  // 创建一个本地副本
    // 先处理选中的选项
    questions[indexFather].selectFlag[indexSoon].flag = !questions[indexFather].selectFlag[indexSoon].flag;
    questions[indexFather].selectAnswer_qutions=questions[indexFather].selectFlag[indexSoon].value
    // 重置其他选项的 flag（如果这是单选逻辑）
    if (questions[indexFather].selectFlag[indexSoon].flag) {
      questions[indexFather].selectFlag.forEach((item, idx) => {
        if (idx !== indexSoon) {
          item.flag = false;
        }
      });
    }
   
    // 更新数据
    this.setData({
      question: questions
    });
    /* console.log(this.data.question); */
  },
  /* 多项选择题 */
  bindSelectduoxuan(e){
    var indexFather = e.currentTarget.dataset.index;
    var indexSoon = parseInt(e.currentTarget.dataset.item) - 1;
    var questions = this.data.question;  // 创建一个本地副本
    // 先处理选中的选项
    questions[indexFather].selectFlag[indexSoon].flag = !questions[indexFather].selectFlag[indexSoon].flag;
    /* begin */
    // 获取当前选项的值
    var value = questions[indexFather].selectFlag[indexSoon].value;
    // 获取当前问题已选答案的字符串
    var currentAnswers = questions[indexFather].selectAnswer_qutions;

    // 检查该值是否已经在字符串中
    if (currentAnswers.includes(value)) {
        // 如果已包含，则从字符串中删除该值
        questions[indexFather].selectAnswer_qutions = currentAnswers.replace(value, "");
    } else {
        // 如果未包含，则添加该值到字符串
        questions[indexFather].selectAnswer_qutions += value;
    }
    /* end */
    /* questions[indexFather].selectAnswer_qutions=questions[indexFather].selectAnswer_qutions+questions[indexFather].selectFlag[indexSoon].value */
    // 重置其他选项的 flag（如果这是单选逻辑）
    /* if (questions[indexFather].selectFlag[indexSoon].flag) {
      questions[indexFather].selectFlag.forEach((item, idx) => {
        if (idx !== indexSoon) {
          item.flag = false;
        }
      });
    } */
    // 更新数据
    this.setData({
      question: questions
    });
    /* console.log(this.data.question); */
  },
  /* 填空题答案填写 */
  fullQutions(e){
      /* console.log(e); */
      var fullItem = e.detail.value
      var index = e.currentTarget.dataset.index
      this.data.question[index].selectAnswer_qutions=fullItem
      this.setData({
          question:this.data.question
      })
      /* console.log(this.data.question); */
  },
  /* 选择模式 */
  change(e){
    wx.showModal({
      title: '是否改变模式？',
      complete: (res) => {
        if (res.confirm) {
            this.setData({
                choose:e.currentTarget.dataset.index
            })
            if(e.currentTarget.dataset.index==0){
                for(var i=0;i<this.data.question.length;i++){
                    this.data.question[i].showAnswer=false
                    this.setData({
                        question:this.data.question
                    })
                }
            }if(e.currentTarget.dataset.index==1){
                for(var i=0;i<this.data.question.length;i++){
                    this.data.question[i].showAnswer=true
                    this.setData({
                        question:this.data.question
                    })
                }
            }
        }
      }
    })
    
  },
  /* 选择 */
  notSelect(){
      wx.showToast({
        title: '选错或背题模式下无法作答',
        icon:'none'
      })
  },
  /* 返回 */
  back(){
    wx.showModal({
        title:'保存做题信息?',
        success:(res)=>{
            if(res.confirm){
                this.subMitEx()
            }if(res.cancel){
                wx.navigateBack()
            }
        }
    })
    
  },
  /* 选项 */
  selectAnswer(e){
     const { index, soonindex, soonitem } = e.currentTarget.dataset;
     console.log(index,soonindex,soonitem);
     /* 获取正确答案 */
     let question = this.data.question;
     const correctAnswer = question[index].answerDetails[0].answerSelect;
      // 更新用户选择的答案和显示状态
    question[index].userAnswer = soonitem;
    question[index].showAnswer = true;
    question[index].isCorrect = (soonitem === correctAnswer);
     // 如果答案正确，则自动跳到下一个题目
     if (soonitem === correctAnswer) {
        this.setData({
          currentQuestionIndex: index + 1,
          answerCorrect:this.data.answerCorrect+1
        });
      }if (soonitem !== correctAnswer) {
        // 如果答案错误
        //更新缓存
        this.data.errorFlag[index].flag=false
        this.setData({
            errorFlag:this.data.errorFlag,
            answerError:this.data.answerError+1
        })
        /* console.log(this.data.errorFlag); */
        //加入数据库
        this.saveMistake(question[index], soonitem);
      }
      this.setData({ question });

  },
  saveMistake: function(questionItem, userAnswer) {
      wx.showLoading({
        title: '错题',
      })
    const db = wx.cloud.database();
    const mistake = {
      questionId: questionItem, // 假设每个题目有唯一的ID
      userAnswer: userAnswer,
      correctAnswer: questionItem.answerDetails[0].answerSelect,
      time: db.serverDate() // 使用服务器时间
    };
    db.collection('mistake').add({
      data: mistake,
      success: res => {
          wx.hideLoading()
        console.log('错题信息已保存', res);
      },
      fail: err => {
          wx.hideLoading()
        console.error('保存错题信息失败', err);
      }
    });
  },
  /* 加入收藏 */
  collectEx(e){
    var index = this.data.current
    var temp = this.data.question[index].id
    var titleShow = this.data.question[index].titleStyle
    wx.request({
      url:app.globalData.baseUrl+ '/user/add_collect',
      method:"POST",
      data:{
          exid:temp,
          userid:wx.getStorageSync('userInfo').id,
          titleShow:titleShow
      },success:(res)=>{
         wx.hideLoading()
         if(res.data.success==true){
            wx.showToast({
              title: '收藏成功',
            })
         }else{
            wx.hideLoading()
            wx.showToast({
              title: 'server Error',
            })
         }
      },fail:(res)=>{
          wx.hideLoading()
          wx.showToast({
            title: 'server Error',
          })
      }
    })

    
      
  },
  /* 上传笔记图片 */
  chooseImg: function() {
    let that = this;
    wx.chooseMedia({
      count: 3,  // 最多可以选择的图片张数
      mediaType: ['image'],
      sizeType: ['original', 'compressed'],  // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'],  // 可以指定来源是相册还是相机，默认二者都有
      camera: 'back',
      success: function(res) {
        // tempFilePaths 是图片的本地临时文件路径列表
        console.log(res);
        const tempFilePaths = res.tempFiles;
        tempFilePaths.forEach(path => {
          wx.uploadFile({
            url:app.globalData.baseUrl + '/user/uploadnotes',  // 你的上传图片接口地址
            filePath: path.tempFilePath,
            name: 'file',
            success: function(uploadRes) {
              const data = JSON.parse(uploadRes.data);
              if (data.success) {
                that.setData({
                    notebook: that.data.notebook.concat(app.globalData.baseUrl+data.url)  // 将返回的地址存储起来
                });
                wx.showToast({
                  title: '上传成功',
                  icon: 'success'
                });
                console.log(that.data.notebook);
              } else {
                wx.showToast({
                  title: '上传失败',
                  icon: 'none'
                });
              }
            },
            fail: function(error) {
              wx.showToast({
                title: '上传错误',
                icon: 'none'
              });
            }
          });
        });
      }
    });
  },
  bindWriteNotes(){
      console.log('触发');
      this.setData({
        showModul:true
      })
  },
  closeModul(){
    this.setData({
        showModul:false
    })
  },
  card(){
    console.log(this.data.errorFlag);
    this.setData({
        showModulCard:true
    })
  },
  closeModulCard(){
    this.setData({
        showModulCard:false
    })
  },
  /* 跳转到 */
  navExIndex(e){
      var index = e.currentTarget.dataset.index
      this.setData({
           currentQuestionIndex:index,
           showModulCard:false
      })
  },
  /* 多选题判断 */
  selectMultipleOption(e){
      const {index,soonitem,soonindex }= e.currentTarget.dataset

      /* console.log(index,soonitem,soonindex); */

      var answer = this.data.question[index].answerDetails

     /*  console.log(answer); */

      let exits= answer.some(item=>item.answerSelect===soonitem)
     
     /*  console.log(exits); */

      if(exits==false){
         this.data.question[index].showAnswer=true
         this.data.question[index].answerFlag[soonindex].flag=false
         this.data.errorFlag[index].flag=false
         this.setData({
             question:this.data.question,
             answerError:this.data.answerError+1,
             errorFlag:this.data.errorFlag
         })
         /* console.log(this.data.question); */
      }if(exits==true){
            this.data.question[index].showAnswer=false
            this.data.question[index].answerFlag[soonindex].flag=true
            this.setData({
                question:this.data.question
            })
            let count = this.data.question[index].answerFlag.filter(item=>item.flag==true).length
            /* console.log(count); */
            if(count==this.data.question[index].answerDetails.length){
                this.data.question[index].showAnswer=true
                wx.showToast({
                  title: '回答正确',
                })
                this.setData({
                    question:this.data.question,
                    currentQuestionIndex: index + 1,
                    answerCorrect:this.data.answerCorrect+1
                })
            }
           /*  console.log(this.data.question); */
      }
  },
  /* 提交答题信息 */
  subMitEx(){
      wx.showModal({
          title:'确定交卷?',
          success:(e)=>{
              if(e.confirm){
                // 答题时间
                const now = new Date();
                const yearNow = now.getFullYear();   // 获取年份
                const monthNow = now.getMonth() + 1; // 获取月份（注意月份从 0 开始，所以需要加 1）
                const dayNow = now.getDate();        // 获取日期
                const hoursNow = now.getHours();     // 获取小时
                const minutesNow = now.getMinutes(); // 获取分钟
                const secondsNow = now.getSeconds(); // 获取秒钟
                const currentTime=yearNow+'-'+monthNow+'-'+dayNow+' '+hoursNow+':'+minutesNow+':'+secondsNow
                console.log('提交时间',currentTime);
                // 题库总数量
                var questionsTemp = this.data.question;
                var countInfo = {};
                // 题库总数量
                countInfo.sum = this.data.question.length;
                // 有效作答题数
                var effective_answer_part = 0;
                // 实际作答题数
                var actual_answer_part = 0;
                // 正确数量
                var correct_num = 0;
                // 错误数量
                var error_num = 0;

                for (var i = 0; i < questionsTemp.length; i++) {
                    questionsTemp[i].judgeFlag = "";
                    if (['单选题', '多选题', '不定项选择题', '填空题'].includes(questionsTemp[i].question_type)) {
                        effective_answer_part += 1;
                        if (this.checkAnswers(questionsTemp[i].selectAnswer_qutions, questionsTemp[i].correct_answer,questionsTemp[i].question_type)) {
                            correct_num += 1;
                            questionsTemp[i].judgeFlag = true;
                        } else {
                            error_num += 1;
                            questionsTemp[i].judgeFlag = false;
                        }
                    }
                    if (questionsTemp[i].selectAnswer_qutions.length != 0) {
                        actual_answer_part += 1;
                    }
                }

                // 本次正确率
                var accuracy_rate = actual_answer_part > 0 ? parseFloat((correct_num / actual_answer_part).toFixed(2)) : 0;
                console.log("题库内容", questionsTemp);
                console.log("有效作答数", effective_answer_part, "实际作答数", actual_answer_part, "正确数量", correct_num, "错误数量", error_num, "正确率", accuracy_rate);
                //加入集合
                countInfo.questions=questionsTemp
                countInfo.effective_answer_part=effective_answer_part
                countInfo.actual_answer_part=actual_answer_part
                countInfo.correct_num=correct_num
                countInfo.error_num=error_num
                countInfo.accuracy_rate=accuracy_rate
                countInfo.subTime=currentTime
                console.log("数据清洗结果",countInfo);
                app.globalData.examCountInfo=countInfo
                wx.navigateTo({
                  url: '/pages/examsub/examsub',
                })
              }if(e.cancel){
                  wx.showToast({
                    title: '取消交卷',
                    icon:"none"
                  })
              }
          }
      })
  },
  isUrl(str) {
    const pattern = /^(http|https):\/\/[^ "]+$/;
    return pattern.test(str);
 },
    /* 底部弹出 */
    handleShowBasic() {
        console.log("触发");
        this.setData({
            closeVisible: true,
        });
    },
    /* 关闭窗口 */
    handlePopupClose() {
        this.setData({
            basicVisible: false,
            scrollVisible: false,
            closeVisible: false,
        });
    },
    /* 打开动作面板 */
    handleOpenBasic(){
        this.setData({
            visible1:true
        })
    },
    /* 关闭控制面板 */
    handleCloseBasic(){
        this.setData({
            visible1:false
        })
    },
    /* 改变护眼模式 */
    handleAction(item, index, e) {
        const [clickItem, clickIndex] = item.detail;
        //@ts-ignore
        wx.showToast({
            title: "模式改变",
            icon:"none"
        });
        if(clickItem.key=="light"){
            this.setData({
                bgColor:"#ffffff",
                font_Color:"#000000"
            })
        }else if(clickItem.key=="night"){
            this.setData({
                bgColor:"#2e2e2e",
                font_Color:"#ffffff"
            })
        }else{
            this.setData({
                bgColor:"#98af81"
            })
        }
    },
    /* 判断答案是否为正确错误 */
    checkAnswers(selectAnswer, correctAnswer,question_type) {
        console.log(question_type);
        if(question_type=='填空题'){
            console.log(selectAnswer ,correctAnswer,selectAnswer==correctAnswer);
            return selectAnswer ===correctAnswer
        }
        // 将字符串转换为字符数组，并进行排序
        let sortedSelectAnswer = selectAnswer.split('').sort().join('');
        let sortedCorrectAnswer = correctAnswer.split('').sort().join('');
        // 比较排序后的字符串
        return sortedSelectAnswer === sortedCorrectAnswer;
    },
    /* 查看题目 */
    checkTitltDetail(e){
        var url = e.currentTarget.dataset.url
        console.log(url);
        wx.previewImage({
          urls: [url],
        })
    },
    checkExplain(e){
        var url = e.currentTarget.dataset.urlSoon
        wx.previewImage({
          urls: [url],
        })
    }
})
